const service = require('../service/ServerSendEvent')
const utils = require('../utils')
const controller = require("./index");

//  获取
exports.getServerDate = (req, res) => {
  res.setHeader('Content-Type', 'text/event-stream')
  res.setHeader('Cache-Control', 'no-cache')
  res.setHeader('Access-Control-Allow-Origin', '*'); // 允许跨域请求
  res.flushHeaders()  //  及时发送刷新响应头

  let clientId = service.createClient(res)

  const interval = setInterval(() => service.getServerDate(res, clientId), 1000)

  req.on('close', () => {
    service.destroyClient(clientId)
    clearInterval(interval)
  })
}

exports.postServerMessage = (req, res) => {
  const { clientId, message} = req.body
  if (clientId) {
    const isSuccess = service.postServerMessage(clientId, message)

    if (isSuccess) {
      res.send(controller.successParams({ msg: '发送成功！' }))
    } else {
      res.send(controller.errorParams({ msg: `发送失败，找不到clientId ${clientId}` }))
    }

  } else {
    res.send(controller.errorParams({ msg: 'clientId 不能为空！' }))
  }
}
